<template>
  <div>
    <div v-show="noData" class="no-data-show">
      <no-data size="200px"></no-data>
    </div>
    <div v-show="!noData">
      <el-form :model="testData" class="interface-test">
        <el-form-item label="接口地址">
          <el-input v-model="intfAddress" placeholder="接口地址eweqwe" class="intf-addr"></el-input>
          <el-button type="primary" @click="submitServer">提交</el-button>
          <!-- <el-button type="default" @click="resetData">重置</el-button> -->
        </el-form-item>

        <!--  post-form-data方式测试 -->
        <el-row class="post-form-type" v-if="showFrom">
          <el-table :data="tableData" style="width: 66%" border>
            <el-table-column label="key" width="180" height="40" class="form-item">
              <template slot-scope="scope">
                <span>{{ scope.row.name }}</span>
              </template>
            </el-table-column>
            <el-table-column label="value">
              <template slot-scope="scope">
                <el-upload v-if="scope.row.files" action="http://localhost:8080" :on-remove="handleRemove" :on-change="handleChange" multiple :show-file-list="true" :file-list="scope.row.files" :auto-upload="false">
                  <el-button slot="trigger" size="small" type="primary" @click="clickRow(scope.$index)">选取文件</el-button>
                  <span slot="tip" class="show-num">选择{{ scope.row.files.length}}个文件</span>
                </el-upload>
                <div v-else>
                  <el-input :value="scope.row.example" @input="changeRowValue(scope.$index, $event)" placeholder="value" class="input-host"></el-input>
                </div>
              </template>
            </el-table-column>

          </el-table>
        </el-row>
        <el-row v-else>
          <el-form-item label="入参字符串"></el-form-item>
          <el-form-item>
            <el-input v-model="testData.inParams" type="textarea" class="record-param" rows="10" resize="none"></el-input>
          </el-form-item>
        </el-row>

        <el-form-item label="响应结果参数"></el-form-item>
        <el-form-item>
          <el-input v-model="outputData" readonly type="textarea" class="record-param" rows="10" resize="none"></el-input>
        </el-form-item>
        <el-row>
        </el-row>
      </el-form>
    </div>
  </div>
</template>

<script>
import { request } from "@/js/_x/utils/request";
import { mapState, mapMutations } from 'vuex'
import NoData from "../../../common/noData"
import axios from "axios";

export default {
  name: "test",
  props: ["testTime"],
  components: {
    NoData
  },
  computed: {
    ...mapState({
      currentProject: state => state.aside.currentProject,
      currentIntf: state => state.aside.currentIntf,
      hostValue: state => state.rightTop.hostValue
    }),
    showFrom: function () {
      if (this.testData.method === "get" || (this.testData.method === "post" && this.testData.way === "form")) {
        return true
      } else {
        return false
      }
    },
    intfAddress: {
      get () {
        return `${this.hostValue}/${this.testData.intfAddress}`
      },
      set (value) {
        // 截取出第三个/ 后面的数据在分别设置
        let index = this.findIndex(value, "/", 4)
        if (index !== -1) {
          this.testData.intfAddress = value.substring(index + 1)
          this.changeHostValue(value.substring(0, index))
        }
      }
    },
    trueAddr () {
      return this.testData.intfAddress.replace(this.hostValue, "")
    }
  },
  watch: {
    testTime: function () {
      this.getInterfaceInfo()
      console.log(this.hostValue)
    },
    currentIntf: function () {
      this.outputData = ""
      this.getInterfaceInfo()
    }
  },
  data () {
    return {
      noData: true,
      currentRow: 0,
      type: "form",
      outputData: "",
      axiosIns: null,
      testData: {
        addr: "",
        inputParams: "",
        outputData: "",
        fileList: []
      },
      // {name: "11", remark: "11", isRequire: false, type: "text", example: "11"}
      tableData: []
    };
  },
  methods: {
    ...mapMutations("rightTop", {
      changeHostValue: "changeHostValue"
    }),
    // 查找出子串在父串的第几次的位置
    findIndex (str, flag, count) {
      let resultIndex = -1;
      for (let i = 0; i < count; i++) {
        resultIndex = str.indexOf(flag, resultIndex + 1)
        if (resultIndex === -1) {
          break
        }
      }
      return resultIndex
    },
    // 获取接口信息
    getInterfaceInfo () {
      let params = {
        projectName: this.currentProject,
        id: this.currentIntf.id
      }
      request("api/interface/node/get_interface_data", params, resp => {
        // console.log(resp)
        this.handleSuccessData(resp)
      }).catch(error => {
        console.log(error)
        this.noData = true
      })
    },
    changeRowValue (index, e) {
      this.$set(this.tableData[index], "example", e);
    },
    clickRow (index) {
      this.currentRow = index;
    },
    handleRemove (file, files) {
      this.$set(this.tableData[this.currentRow], "files", files);
    },
    handleChange (file, files) {
      /* 将文件数据添加到tableData上 */
      this.$set(this.tableData[this.currentRow], "files", files);
    },
    handleFiles (files) {
      let newFiles = [];
      files.forEach((item, index) => {
        newFiles.push(item.raw);
      });
      return newFiles;
    },
    submitServer () {
      /* //创建axios实例 */
      this.axiosIns = axios.create({
        baseURL: this.hostValue
      });
      // 判断提交类型
      if (this.testData.method === "get") {
        // 发起get请求
        this.sendGet()
      } else if (this.testData.method === "post") {
        if (this.testData.way === "form") {
          this.sendPostForm()
        } else if (this.testData.way === "json") {
          // json请求
          this.sendPostJson()
        }
      }
    },
    // 发送get请求  
    sendGet () {
      let formDataObj = new FormData();
      for (let index in this.tableData) {
        let o = this.tableData[index]
        /* //针对，如果是文件上传的话，特殊处理 */
        if (o["files"]) {
          let newFiles = this.handleFiles(o["files"])
          newFiles.forEach(item => {
            formDataObj.append("files", item)
          })
        } else {
          formDataObj.append(o["name"], o["example"])
        }
      }
      let axiosObj = this.axiosIns.get(`${this.trueAddr}`, `${JSON.stringify({ params: formDataObj })}`);
      axiosObj.then(Response => {
        this.handleSuccess(Response.data)
      }).catch(error => {
        this.handleError(error)
      })
    },
    // 发送form表单请求
    sendPostForm () {
      let formDataObj = new FormData();
      for (let index in this.tableData) {
        let o = this.tableData[index]
        /* //针对，如果是文件上传的话，特殊处理 */
        if (o["files"]) {
          let newFiles = this.handleFiles(o["files"])
          newFiles.forEach(item => {
            formDataObj.append("files", item)
          })
        } else {
          formDataObj.append(o["name"], o["example"])
        }
      }
      let axiosObj = this.axiosIns.post(`${this.trueAddr}`, formDataObj, { headers: { "Content-Type": 'multipart/form-data' } });
      axiosObj.then(Response => {
        this.handleSuccess(Response.data)
      }).catch(error => {
        this.handleError(error)
      })
    },
    // 发送json请求
    sendPostJson () {
      let config = { headers: { "Content-Type": "application/json" } };
      // 拼接地址
      this.axiosIns.post(`${this.trueAddr}`, `${JSON.parse(this.testData.inParams)}`, config)
        .then(Response => {
          this.handleSuccess(Response.data)
        }).catch(error => {
          this.handleError(error)
        })
    },
    handleError (error) {
      console.log(error)
      this.outputData = ""
      this.$message({ type: "error", message: "后台异常，获取数据失败" })
    },
    handleSuccess (resp) {
      this.$message({ type: "success", message: "获取数据成功!" })
      this.outputData = JSON.stringify(resp, null, 2)
      // if (resp.result) {
      //   this.outputData = JSON.stringify(resp.data, null, 2)
      //   this.$message({ type: "success", message: "获取数据成功!" })
      // } else {
      //   this.$message({ type: "error", message: resp.message })
      //   this.outputData = ""
      // }
    },
    handleSuccessData (resp) {
      if (resp.result && resp.data) {
        this.testData = resp.data
        // this.testData.intfAddress = `${this.hostValue}/${this.testData.intfAddress}`
        // 处理form表单体检文件情况数据
        if (resp.data.method === "get" || (resp.data.method === "post" && resp.data.way === "form")) {
          this.tableData = resp.data.inParams.map(item => {
            if (item.type === "file") {
              item.files = []
            }
            return item
          })
        }
        console.log(this.tableData)
        this.noData = false
      } else {
        this.noData = true
      }
    }
  }
};
</script>

<style lang="scss" scoped>
@import "~@/assets/styles/home/content/intf-test.scss";
</style>
